#include "httpServer.hpp"
#include "httpProtocol.hpp"

#include <iostream>
#include <memory>

void Usage(char *command)
{
    std::cout << "Usage:\n\t" << command << "\tserver_port\n\t" << std::endl;
}

std::string suffixToDescribe(const std::string &suffix)
{
    std::string ct = "Content-Type: ";
    if (suffix == ".html")
        ct += "text/html";
    else if (suffix == ".png")
        ct += "image/png";
    else
        ct += "text/html";
    ct += "\r\n";
    return ct;
}

bool httpTest(httpRequest &request, httpResponse &response)
{
    std::cout << "------------------------http request start------------------------------" << std::endl;
    std::cout << request.inbuffer;
    cout << "method: " << request.method << endl;
    cout << "url: " << request.url << endl;
    cout << "version: " << request.version << endl;
    cout << "path: " << request.path << endl;
    cout << "suffix: " << request.suffix << endl;
    cout << "size: " << request.size << endl;
    std::cout << "------------------------http request end------------------------------" << std::endl;

    /*逻辑处理之后，需要返回响应*/
    std::string responseLine = "HTTP/1.1 301 OK\r\n"; /*请求行硬编码...TODO*/
    std::string responseHeader = suffixToDescribe(request.suffix);
    std::string responseBlank = "\r\n";
    std::string responseBody;
    //responseHeader += "Location: https://www.baidu.com/\r\n";
    int contentSize = request.size;

    /*开始逻辑处理*/
    if (!Util::readFile(request.path, responseBody, contentSize))
    {
        Util::readFile(page404, responseBody, contentSize);
    }

    /*响应返回的正文大小要至少多1
     *个人理解：如果响应正文大小刚好为正文大小，那么客户端在做解释的时候就刚好解释完，不会有后续动作*/
    responseHeader += "Content-Length: " + std::to_string(contentSize + 1) + "\r\n";
    responseHeader += "Set-Cookie: 123456test\r\n";

    /*序列化响应结果*/
    response.outbuffer += responseLine;
    response.outbuffer += responseHeader;
    response.outbuffer += responseBlank;
    cout << response.outbuffer << endl;

    response.outbuffer += responseBody;

    return true;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(-1);
    }
    uint16_t port = std::stoi(argv[1]);
    std::unique_ptr<httpServer> uphs(new httpServer(httpTest, port));
    // uphs->registerCallBack("./wwwroot/index.html", httpTest);
    // uphs->registerCallBack("./wwwroot/test/a.html", httpTest);
    // uphs->registerCallBack("./wwwroot/test/b.html", httpTest);
    // uphs->registerCallBack("./wwwroot/test/c.html", httpTest);
    // uphs->registerCallBack("./wwwroot/image/1.png", httpTest);
    // uphs->registerCallBack("./wwwroot/logOn", httpLogOn);

    uphs->initServer();
    uphs->start();
    return 0;
}